import axios from "axios";
import $utils from "@/utils/utils";

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 10000,
});
// request拦截器
service.interceptors.request.use(
  (config) => {
    // todo  需要改进
    // 设置mock接口不走前缀
    if (config.url.indexOf("/mock/") === 0) {
      config.baseURL = "";
    }
    const token = $utils.localStorage.getItem("token");
    if (token) {
      config.headers = {
        Authorization: "bearer " + token,
      };
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);
// 响应拦截器
service.interceptors.response.use(
  (res) => {
    const { data } = res;
    if (data.code === 200) {
      if (data.result) {
        return data.result;
      } else {
        return data;
      }
    } else {
      return Promise.reject(res.data);
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);
const $http = {
  request: service,
};
export default $http;
